package com.xh.bussiness.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.io.Files;
import com.xh.bussiness.system.service.IFileListService;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.exception.XhException;
import com.xh.core.properties.XhProperties;
import com.xh.core.util.DateUtils;
import com.xh.core.util.FileUtils;
import io.swagger.annotations.Api;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by qin98 on 2016/9/3.
 */
@Api(tags="ueditor配置处理类")
@Controller
@CrossOrigin
@RequestMapping("/system/ueditor")
public class UEditorUploadController {

	@Autowired
	ApplicationContext applicationContext;
	@Autowired
	private XhProperties xhProperties;
	@Autowired
	private IFileListService fileListService;

	@RequestMapping("/index")
	@ExcludeLoginTokenIntercept
	public void index(String action, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if (StringUtils.isBlank(action)) {
			throw new XhException("action is null");
		}
		if ("config".equals(action)) {
			OutputStream os = response.getOutputStream();
			IOUtils.copy(UEditorUploadController.class.getClassLoader().getResourceAsStream("config/ueditor_config.json"), os);
		} else {
			request.getRequestDispatcher(action).forward(request, response);
		}

	}

	@RequestMapping("/uploadimage")
	@ExcludeLoginTokenIntercept
	@ResponseBody
	public Map<String, String> uploadImage(HttpServletRequest request, HttpServletResponse response, MultipartFile upload,String responseType) {
		Map<String, String> result = new HashMap<>();
		String state = "SUCCESS";
		if (!upload.isEmpty()) {
			if(xhProperties.getEditor().getUeditor().getUploadTarget().equals("server")){

				String uploadPath=request.getSession().getServletContext().getRealPath("/");
				String relativePath="upload"+"/";
				String customPath=xhProperties.getEditor().getUeditor().getImagePath();
				if(!com.xh.core.util.StringUtils.isEmpty(customPath)){
					relativePath+=customPath+"/";
				}
				Date now =new Date();
				relativePath+= DateUtils.format(now,"yyyyMM")+"/";
				relativePath+= DateUtils.format(now,"dd")+"/";

				String newFilename= FileUtils.randomRenameFilename(upload.getOriginalFilename());

				uploadPath+=relativePath;
				result.put("originalFilename",upload.getOriginalFilename());
				result.put("savePath","/"+relativePath+newFilename);

				File saveFile = new File(uploadPath, newFilename);
				if (!saveFile.getParentFile().exists()) {
					saveFile.getParentFile().mkdirs();
				}
				try {
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
					//out.write(file.getBytes());
					InputStream is=upload.getInputStream();
					byte[] buffer = new byte[1024];
					int i = -1;
					while ((i = is.read(buffer)) != -1) {
						out.write(buffer, 0, i);

					}
					out.flush();
					out.close();

					result.put("uploaded", "1");
					result.put("url", "/test/" + relativePath + newFilename);
					System.out.println("************************"+relativePath + newFilename);
					result.put("size", String.valueOf(upload.getSize()));
					result.put("type", Files.getFileExtension(upload.getOriginalFilename().toLowerCase()));
					result.put("state", state);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				/**
				String suffix = upfile.getOriginalFilename().substring(upfile.getOriginalFilename().lastIndexOf("."));
				String fileId = null;
				try {
					fileId = QiniuDFSManager.public_upload(upfile.getBytes(), image_path, UUID.randomUUID().toString()+suffix);
					String path = QiniuDFSManager.public_download(fileId);
					String state = "SUCCESS";
					result.put("url", path);
					result.put("size", String.valueOf(upfile.getSize()));
					result.put("type", suffix);
					result.put("state", state);
				} catch (IOException e) {
					e.printStackTrace();
				}
				 */
			}
		}
		return result;
	}

	@RequestMapping("/upload-file")
	@ExcludeLoginTokenIntercept
	@ResponseBody
	public Map<String, String> uploadFile(HttpServletRequest request,MultipartFile upfile) {
		String file_path = xhProperties.getEditor().getUeditor().getFilePath();
		return uploadFile(request,upfile, file_path);
	}

	@RequestMapping("/upload-video")
	@ResponseBody
	public Map<String, String> uploadVideo(HttpServletRequest request,MultipartFile upfile) {
		String file_path = xhProperties.getEditor().getUeditor().getFilePath();
		return uploadFile(request,upfile, file_path);
	}

	@RequestMapping("/upload-scrawl")
	@ResponseBody
	public Map<String, String> uploadScrawl(HttpServletRequest request,String upfile) {
		Map<String, String> result = new HashMap<>();
		String state = "SUCCESS";
		result.put("url", "data:image/png;base64," + upfile);
		result.put("size", String.valueOf(upfile.length()));
		result.put("type", "");
		result.put("state", state);
		return result;
	}

	@RequestMapping("/upload-catcher")
	@ResponseBody
	public Map<String, String> uploadCatcher(HttpServletRequest request,String source) {
		return null;
	}

	@RequestMapping("/image-list")
	@ResponseBody
	public Map<String, Object> imageList(HttpServletRequest request,Integer start,Integer size) {
		Map<String, Object> result = new HashMap<>();
		List<JSONObject> urls=new ArrayList<>();
		String state = "SUCCESS";
		JSONObject url=new JSONObject();

		url.put("url","/upload/ueditor/image/201812/20/1545265850462886556.png");
		urls.add(url);
		result.put("list",urls);
		result.put("total",1);
		result.put("start", start);
		result.put("state", state);
		return result;
	}

	@RequestMapping("/file-list")
	@ResponseBody
	public Map<String, String> fileList(HttpServletRequest request,String source) {
		return null;
	}

	private Map<String, String> uploadFile(HttpServletRequest request,MultipartFile upfile, String path) {
		Map<String, String> result = new HashMap<>();
		String state = "SUCCESS";
		if (!upfile.isEmpty()) {
			String suffix = upfile.getOriginalFilename().substring(upfile.getOriginalFilename().lastIndexOf("."));
			String fileId;
			try {
				if(xhProperties.getEditor().getUeditor().getUploadTarget().equals("server")){

					String uploadPath=request.getSession().getServletContext().getRealPath("/");
					String relativePath="upload"+"/";
					String customPath=path;
					if(!com.xh.core.util.StringUtils.isEmpty(customPath)){
						relativePath+=customPath+"/";
					}
					Date now =new Date();
					relativePath+= DateUtils.format(now,"yyyyMM")+"/";
					relativePath+= DateUtils.format(now,"dd")+"/";

					String newFilename= FileUtils.randomRenameFilename(upfile.getOriginalFilename());

					uploadPath+=relativePath;
					result.put("originalFilename",upfile.getOriginalFilename());
					result.put("savePath","/"+relativePath+newFilename);

					File saveFile = new File(uploadPath, newFilename);
					if (!saveFile.getParentFile().exists()) {
						saveFile.getParentFile().mkdirs();
					}
					try {
						BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
						//out.write(file.getBytes());
						InputStream is=upfile.getInputStream();
						byte[] buffer = new byte[1024];
						int i = -1;
						while ((i = is.read(buffer)) != -1) {
							out.write(buffer, 0, i);

						}
						out.flush();
						out.close();

						result.put("url", "/" + relativePath + newFilename);
						result.put("size", String.valueOf(upfile.getSize()));
						result.put("type", Files.getFileExtension(upfile.getOriginalFilename().toLowerCase()));
						result.put("state", state);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}else{
					/**
					fileId = QiniuDFSManager.public_upload(upfile.getBytes(), uploadPath, UUID.randomUUID().toString().replaceAll("-", "") + suffix);
					String path = QiniuDFSManager.public_download(fileId);
					result.put("url", path);
					result.put("size", String.valueOf(upfile.getSize()));
					result.put("type", suffix);
					result.put("state", state);
					result.put("filename", upfile.getOriginalFilename());
					 */
				}
			} catch (Exception e) {
				throw new XhException("error");
			}
		}
		return result;
	}

	@RequestMapping("/show")
	public void show(String filePath, HttpServletResponse response) throws IOException {

		File file = new File(filePath);

		response.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 60 * 60 * 24);
		response.setHeader("Cache-Control", "max-age=60");
		OutputStream os = response.getOutputStream();

		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
			IOUtils.copy(is, os);
		} catch (FileNotFoundException e) {
			response.setStatus(404);
			return;
		} finally {
			if (null != is) {
				is.close();
			}
			if (null != os) {
				os.flush();
				os.close();
			}
		}
	}
}
